package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${uploadFile.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //获取上传的文件的文件名
        String fileName = file.getOriginalFilename();
        //解析得到后缀名
        String endName = fileName.substring(fileName.lastIndexOf("."));
        //生成UUID,作为新的文件名,防止上传的文件重名问题
        String newName = UUID.randomUUID().toString() + endName;

        //将上传的文件拷贝到服务器指定位置
        file.transferTo(new File(path, newName));
        return R.success(newName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //1. 根据下载的文件名,找到对应文件, 通过响应流将数据写回客户端
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(path,name)));
        //设置响应的mime类型
        response.setContentType("image/jpeg");
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());

        //2. 定义临时变量,作为传输载体
        byte[] bys = new byte[1024];
        int len;

        //3. 循环读写
        while ((len = bis.read(bys)) != -1){
            bos.write(bys,0,len);
            bos.flush();
        }

        //4. 关闭io,释放资源
        bis.close();
        bos.close();
    }
}
